import { ApesModalService } from '@shared/apes/modal';
import { ApesDrawerService } from '@shared/apes/drawer';
import { ApiService } from '@core/services/http/api.service';
import { ApesContextMenuComponent } from './context-menu.component';
import { Events } from '@core/services/events/Events';
import { Router } from '@angular/router';
import { ReuseTabService } from '@shared/apes/reuse-tab';
import * as CryptoJS from 'crypto-js';
import { Injectable } from '@angular/core';
import { ApesMessageService } from '@shared/apes/message';
import { isObject } from 'app/utils/utils';
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs/index';
import {FormService} from "@core/services/form.service";

@Injectable({
  providedIn: 'root',
})
export class ApesContextMenuService {

  dialogRef: any;
  drawerRef: any;

  constructor(private apiService: ApiService,
              private drawerService: ApesDrawerService,
              private router: Router, private event: Events,
              protected rs: ReuseTabService,
              private msg: ApesMessageService,
              private modalService: ApesModalService,
              private formService: FormService) {
  }

  openContextDailog(params: any, callback: any, config?: any, dialog?: any): void {
    const openDialog = dialog ? dialog : ApesContextMenuComponent;
    this.dialogRef = this.modalService.create({
      apesWidth: config.width ? config.width : 520,
      apesMaskClosable: config.maskClosable ? config.maskClosable : true,
      apesClosable: config.closable ? config.closable : true,
      apesTitle: config.title,
      apesContent: openDialog,
      apesComponentParams: params,
      apesFooter: [
        // {
        //   label: '取消',
        //   type: 'default',
        //   onClick: () => {
        //     this.dialogRef.close();
        //   },
        // },
        {
          label: '确定',
          type: 'primary',
          onClick: () => {
            this.dialogRef.destroy();
          },
        },
      ],
    });
  }

  openContextDynamicDailog(params: any, api: any, key: any, callback: any, config?: any, dialog?: any):void {
    const openDialog = dialog ? dialog : ApesContextMenuComponent;
    const info ={
      width:'70vw',//1200
      maskClosable:true,
      closable:true
    };
    if(config){
      info.width = config.width;
      info.maskClosable = config.maskClosable;
      info.closable = config.closable;
    }
    this.apiService.post('form.search.get', {
      'body': JSON.stringify({ 'id': api}),
    }).pipe().subscribe(
      (body) => {
        body.result = [];
        body.params = params;
        body.key = key;
        // body.formId = "purch.order";
        this.dialogRef = this.modalService.create({
          apesWidth: info.width,
          apesMaskClosable: info.maskClosable,
          apesClosable: info.closable,
          apesTitle: body.title,
          apesContent: openDialog,
          apesComponentParams: body,
          apesFooter: [
            // {
            //   label: '取消',
            //   type: 'default',
            //   onClick: () => {
            //     dialogRef.close();
            //   },
            // },
            {
              label: '确定',
              type: 'primary',
              onClick: (componentInstance) => {
                this.dialogRef.destroy(componentInstance['resultData']);
              },
            },
          ],
        });
        return this.dialogRef.afterClose.subscribe((result) => callback(result));
      }
    )
  }

  openContextDrawer(params: any, callback: any, config?: any, drawer?: any): void {
    const openDrawer = drawer ? drawer : ApesContextMenuComponent;
    this.drawerRef = this.drawerService.create({
      apesWidth: config.width ? config.width : 520,
      apesHeight: config.height,
      apesPlacement: config.placement ? config.placement : 'right',
      apesMaskClosable: config.maskClosable ? config.maskClosable : true,
      apesClosable: config.closable ? config.closable : true,
      apesTitle: config.title,
      apesContent: openDrawer,
      apesContentParams: params,
    });
  }

  switchLink(url,formId,data,params){
    // 混合额外的参数(可能存在覆盖的情况)
    if (isObject(params)) Object.assign(data, params);
    if (this.rs.exists(url) || this.rs.curUrl === url) {
      this.event.publish(formId, data);
      this.event.publish('drawer'); // 用于处理弹框跳连接弹框关闭
      this.router.navigateByUrl(formId);
    } else {
      let value = CryptoJS.enc.Utf8.parse(JSON.stringify(data));
      value = CryptoJS.enc.Base64.stringify(value);
      this.event.publish('drawer'); // 用于处理弹框跳连接弹框关闭
      this.router.navigate([formId], { queryParams: { value: value } });
    }
  }

  openContextLink(data: any, method: string, params?: object) {
    if (isObject(params)) Object.assign(data, params);
    if (method == null) {
      this.msg.error('该链接尚未存在，麻烦核实！', { 'apesDuration': 5000 });
      return false;
    }
    if(params['OAInterface'] == false){
      const formId = method;
      data['formId'] = formId;
      this.formService.navigateToForm(data);
      return;
    }
    this.apiService.post(method, { 'body': JSON.stringify(data) }).subscribe((item) => {
      if( data.changeSignFlag ) item.changeSignFlag = data.changeSignFlag;
      if( data.wfFlag ) item.wfFlag = data.wfFlag;
      if( data.OAInterface ) item.OAInterface = data.OAInterface;

      this.formService.navigateToForm(item);
    });
  }
}
